<?php
declare (strict_types=1);
namespace app\api\controller\v1\untils;

use app\admin\model\DataAccountMsms;
use GuzzleHttp\Psr7\HttpFactory;
use think\Http;

/**
 *
 * Class LoginServices
 * @package app\services\user
 */
class SmsServices
{
    private $sms_url = 'https://api-v4.mysubmail.com/sms/send';
    /**/
    private $appid = '';
    private $appkey = '';
    private $signature_name = '';


    /**
     * 根据场景配置发送验证码
     * @param string $scene 业务场景
     * @param string $phone 手机号码
     * @param array $params 模板变量
     * @param array $options 其他配置
     */
    public function verify(string $scene, string $phone, array $params = [], array $options = [])
    {
        $data = [
            'mobile' => $phone,
            'content' => '您的验证码是：'.$params['code'].'，请在5分钟内输入',
        ];
        $result = $this->httpSendSms($data);
//        $result = '{"status": "success","send_id": "893c91d9bfaa433f6952b2902546a8ed","fee": 1}';
        DataAccountMsms::mk()->save([
//            'unid'   => intval(sysvar('plugin_account_user_unid')),
//            'usid'   => intval(sysvar('plugin_account_user_usid')),
            'type'   => class_basename(static::class),
            'smsid'  => $result['send_id'] ?? '',
            'scene'  => $scene,
            'phone'  => $phone,
            'status' => 1,
            'result' => $result,
            'params' => json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
        ]);
        return $result;
    }
    /*请求接口*/
    public function httpSendSms($data=[])
    {
        $http_arr = [
            'appid' => $this->appid,
            'to' => $data['mobile'],
            'content' => $this->signature_name.$data['content'],
            'timestamp' => time(),
            'sign_type' => 'sha1',
            'sign_version' => 2,
        ];
        /*创建签名*/
        $http_arr['signature'] = $this->httpCreateSing($http_arr);
        $options['headers'] = ['Content-Type: application/json; charset=utf-8'];

        $send_res = H::post($this->sms_url, json_encode($http_arr), $options);
        /*写入日志*/
        $this->log_write_fdump([$http_arr,$send_res],'send/sms',1);
        return $send_res;
    }
    /*创建远程签名*/
    public function httpCreateSing($data=[])
    {
        $arr = [
            'timestamp' => $data['timestamp'],
            'sign_type' => $data['sign_type'],
            'sign_version' => $data['sign_version'],
            'appid' => $this->appid,
            'to' => $data['to'],
        ];
        ksort($arr);
        $str = $this->appid.$this->appkey;
        foreach ($arr as $k=>$v)
        {
            $str .= $k.'='.$v.'&';
        }
        $str = rtrim($str,'&');
        $str .= $this->appid.$this->appkey;
        return sha1($str);
    }
    protected function log_write_fdump($data, $filename='test', $append=false)
    {
        $fileName =  runtime_path(). 'logs/' . date('Ymd') . '/' . $filename . '_fdump.php';
        $dirName = dirname($fileName);
        if(!file_exists($dirName)){
            mkdir($dirName, 0777, true);
        }
        $debug_trace = debug_backtrace();
        $file = __FILE__ ;
        $line = "unknown";
        if (isset($debug_trace[0]) && isset($debug_trace[0]['file'])) {
            $file = $debug_trace[0]['file'] ;
            $line = $debug_trace[0]['line'];
        }
        $f_l = '['.$file.' : '.$line.']';
        if($append){
            if(!file_exists($fileName)){
                file_put_contents($fileName,'<?php');
            }
            file_put_contents($fileName,PHP_EOL.$f_l.PHP_EOL.date('Y-m-d H:i:s').' '.PHP_EOL.var_export($data,true).PHP_EOL,FILE_APPEND);
        }
        else{
            file_put_contents($fileName,'<?php'.PHP_EOL.date('Y-m-d H:i:s').' '.PHP_EOL.var_export($data,true));
        }
    }
}
